package com.pucong.gitee.database.backup.configuration.quartz;

import com.pucong.gitee.database.backup.configuration.quartz.job.QuartzLogFileTask;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

/**
 * 任务调度处理
 *
 * @author pucong
 */
@Configuration
@Slf4j
public class MyQuartzScheduler {

    @Autowired
    private Scheduler scheduler;

    /**
     * 开始执行所有任务
     *
     * @throws SchedulerException
     */
    public void startJob() throws SchedulerException {
        // 日志文件、临时文件处理
        JobKey quartzLogFileTaskKey = new JobKey("quartzLogFileTask", "quartzLogFileGroup");
        JobDetail quartzLogFileTask = this.scheduler.getJobDetail(quartzLogFileTaskKey);
        if (quartzLogFileTask == null) {
            addTaskJob("quartzLogFileTask", "quartzLogFileGroup", "0 0/10 * * * ?", QuartzLogFileTask.class);
        } else {
            editTaskJobTime("quartzLogFileTask", "quartzLogFileGroup", "0 0/10 * * * ?");
        }
        scheduler.start();
    }

    private void editTaskJobTime(String name, String group, String time) {
        try {
            boolean b = modifyJob(name, group, time);
            if (!b) {
                log.error("修改任务失败");
            }
        } catch (SchedulerException e) {
            log.error("修改任务失败");
        }
    }

    /**
     * 获取Job信息
     *
     * @param name
     * @param group
     * @return
     * @throws SchedulerException
     */
    public String getJobInfo(String name, String group) throws SchedulerException {
        TriggerKey triggerKey = new TriggerKey(name, group);
        CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        return String.format("time:%s,state:%s", cronTrigger.getCronExpression(),
                scheduler.getTriggerState(triggerKey).name());
    }

    /**
     * 修改某个任务的执行时间
     *
     * @param name
     * @param group
     * @param time
     * @return
     * @throws SchedulerException
     */
    public boolean modifyJob(String name, String group, String time) throws SchedulerException {
        Date date = null;
        TriggerKey triggerKey = new TriggerKey(name, group);
        CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        String oldTime = cronTrigger.getCronExpression();
        if (!oldTime.equalsIgnoreCase(time)) {
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(time);
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(name, group)
                    .withSchedule(cronScheduleBuilder).build();
            date = scheduler.rescheduleJob(triggerKey, trigger);
        }
        return date != null;
    }

    /**
     * 暂停所有任务
     *
     * @throws SchedulerException
     */
    public void pauseAllJob() throws SchedulerException {
        scheduler.pauseAll();
    }

    /**
     * 暂停某个任务
     *
     * @param name
     * @param group
     * @throws SchedulerException
     */
    public void pauseJob(String name, String group) throws SchedulerException {
        JobKey jobKey = new JobKey(name, group);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null) {
            return;
        }
        scheduler.pauseJob(jobKey);
    }

    /**
     * 恢复所有任务
     *
     * @throws SchedulerException
     */
    public void resumeAllJob() throws SchedulerException {
        scheduler.resumeAll();
    }

    /**
     * 恢复某个任务
     *
     * @param name
     * @param group
     * @throws SchedulerException
     */
    public void resumeJob(String name, String group) throws SchedulerException {
        JobKey jobKey = new JobKey(name, group);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null) {
            return;
        }
        scheduler.resumeJob(jobKey);
    }

    /**
     * 删除某个任务
     *
     * @param name
     * @param group
     * @throws SchedulerException
     */
    public void deleteJob(String name, String group) throws SchedulerException {
        JobKey jobKey = new JobKey(name, group);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null) {
            return;
        }
        scheduler.deleteJob(jobKey);
    }

    /**
     * 新增一个定时任务
     *
     * @param name
     * @param group
     * @param corn
     * @param cla
     * @throws SchedulerException
     */
    private void addTaskJob(String name, String group, String corn, Class cla) throws SchedulerException {
        // 通过JobBuilder构建JobDetail实例，JobDetail规定只能是实现Job接口的实例
        // JobDetail 是具体Job实例
        JobDetail jobDetail = JobBuilder.newJob(cla).withIdentity(name, group).build();
        // 基于表达式构建触发器 30分钟一次
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(corn);
        // CronTrigger表达式触发器 继承于Trigger
        // TriggerBuilder 用于构建触发器实例
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(name, group)
                .withSchedule(cronScheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }

    /**
     * 新增一个定时任务
     * @param name
     * @param group
     * @param corn
     * @param cla
     * @param taskId
     * @throws SchedulerException
     */
    public void addTaskJob(String name, String group, String corn, Class cla, String taskId) throws SchedulerException {
        // 通过JobBuilder构建JobDetail实例，JobDetail规定只能是实现Job接口的实例
        // JobDetail 是具体Job实例
        JobDetail jobDetail = JobBuilder.newJob(cla).withIdentity(name, group).usingJobData("taskId", taskId).build();
        // 基于表达式构建触发器 30分钟一次
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(corn);
        // CronTrigger表达式触发器 继承于Trigger
        // TriggerBuilder 用于构建触发器实例
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(name, group)
                .withSchedule(cronScheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }
}
